package com.hwy.widget.segment

import android.animation.Animator
import android.animation.ValueAnimator
import android.graphics.Canvas
import android.view.animation.AccelerateDecelerateInterpolator
import androidx.annotation.FloatRange

/**
 * =======================================
 * 作者: hewenyu
 * 日期: 2022/5/4 12:56
 * 说明: Segment滑块
 * =======================================
 */
abstract class AbstractSegmentSlider(val segment: TabSegment) {

    companion object {
        /**
         * 无效的index
         */
        private const val INVALID_INDEX = -1
    }

    /**
     * 滑块滑动起始的位置
     */
    var fromIndex = INVALID_INDEX

    /**
     * 滑块滑动的目标位置
     */
    var toIndex = INVALID_INDEX

    /**
     * 动画进度
     */
    @FloatRange(from = 0.0, to = 1.0)
    var fraction = 1F

    /**
     * 滚动动画
     */
    private val sliderAnimator by lazy {
        ValueAnimator.ofFloat(0F, 1F).apply {
            duration = segment.getDuration()
            interpolator = AccelerateDecelerateInterpolator()
            addUpdateListener {
                (it.animatedValue as? Float)?.run {
                    fraction = this
                    segment.invalidate()
                }
            }
            addListener(object : Animator.AnimatorListener {
                override fun onAnimationStart(animation: Animator?) {

                }

                override fun onAnimationEnd(animation: Animator?) {
                    resetSliderIndex()
                }

                override fun onAnimationCancel(animation: Animator?) {
                    resetSliderIndex()
                }

                override fun onAnimationRepeat(animation: Animator?) {

                }
            })
        }
    }

    fun getAnimator(): ValueAnimator {
        return sliderAnimator
    }

    /**
     * 判断动画是否正在执行
     */
    fun isAnimatorRunning(): Boolean {
        return sliderAnimator.isRunning
    }

    /**
     * 停止动画
     */
    fun stopSlide() {
        sliderAnimator.cancel()
    }

    fun resetSliderIndex() {
        this.fromIndex = INVALID_INDEX
        this.toIndex = INVALID_INDEX
    }

    fun startSlide(from: Int, to: Int) {
        stopSlide()
        this.fromIndex = from
        this.toIndex = to
        sliderAnimator.start()
    }

    /**
     * 绘制滑块
     */
    abstract fun draw(currentIndex: Int, canvas: Canvas)


}